package com.dhh.sky.service;

import java.util.Arrays;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.util.Config;
import com.dhh.sky.util.Constant;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public abstract class BaseService extends IntentService{
	protected SDAApplication app;
	
	public BaseService(String name) {
		super(name);
	}

	@Override
	protected void onHandleIntent(final Intent intent) {
		app = (SDAApplication) this.getApplication();

		if(!isNetworkAvailable()){
			responseConnectError(this.getString(R.string.msg_error_network));
			return;
		}
		
		if(app.isConnected()){
			process(intent);
		}else{
			final LiveAuthClient aClient = new LiveAuthClient(this,Config.CLIENT_ID);
			aClient.initialize(Arrays.asList(Config.SCOPES), new LiveAuthListener(){
	            @Override
	            public void onAuthError(LiveAuthException exception, Object userState) {
	            	responseConnectError(BaseService.this.getString(R.string.msg_error_connect));
	            }

	            @Override
	            public void onAuthComplete(LiveStatus status,LiveConnectSession session,Object userState) {
	                if (status==LiveStatus.CONNECTED) {
	                	app.setAuthClient(aClient);
	                	app.setSession(session);
	                    app.setConnectClient(new LiveConnectClient(session));
	                	process(intent);
	                }else{
	                	responseConnectError(BaseService.this.getString(R.string.msg_error_connect));
	                }
	            }
	        });
		}
		
	}	
	
	public abstract void process(Intent intent);
	
	private boolean isNetworkAvailable(){
		boolean flag = false;
		
		ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
		if (activeNetwork!=null && activeNetwork.isConnected()) {
			flag = true;
		}
		
		return flag;
	}
	
	private void responseConnectError(String msg){
		Intent respone = new Intent(Constant.SERVICE_NAME_CONNECT);
		respone.putExtra(Constant.SERVICE_PARAM_ERROR, true);
		respone.putExtra(Constant.SERVICE_PARAM_MSG, msg);
		sendBroadcast(respone);
	}

}
